package sisicotren.ui.simulator;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.Image;
import sisicotren.ui.simulator.Point;

import java.util.Observable;
import java.util.Observer;

public class ChannelBasicImpl implements Channel, Observer {

	public ChannelBasicImpl(Point p) {
		position = p;
		state = ChannelState.IDLE;
	}
	
	public void draw(Graphics g) {
		Image img = getImageByState();
		g.drawImage(img, 
				(int)position.getX(), 
				(int)position.getY(), 
				this.getWidth(), 
				this.getHeight(),
				Color.ORANGE,
				null);
	}

	private Image getImageByState() {
		if(channelImg == null || channelBusyImg == null) {
			loadImg();
		}
		return state == ChannelState.IDLE ? channelImg : channelBusyImg;
	}
	
	private void loadImg() {
		channelImg = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/channel-normal.png"));
		channelBusyImg = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/channel-busy.png"));
	}
	
	public int getWidth() {
		Image img = getImageByState();
		return img == null ? 0 : img.getWidth(null) == -1 ? 60 : img.getWidth(null);
	}
	
	public int getHeight() {
		Image img = getImageByState();
		return img == null ? 0 : img.getHeight(null) == -1 ? 100 : img.getHeight(null);
	}
	
	public ChannelState getState() {
		return state;
	}

	public void setState(ChannelState state) {
		this.state = state;
	}

	@Override
	public Point getPosition() {
		return this.position;
	}

	@Override
	public void setPosition(Point p) {
		this.position = p;
	}

	
	@Override
	public void update(Observable o, Object arg) {
		switch(((sisicotren.model.simulator.Channel)o).getCurrentState()) {
		case BLOCKED :
			state = ChannelState.BLOCKED;
			break;
		case IDLE :
			state = ChannelState.IDLE;
			break;
		case BUSY :
			state = ChannelState.BUSY;
			break;
		}
	}
	
	public ScreenElement copy(){ 
		ChannelBasicImpl channelCpy = new ChannelBasicImpl(new Point(this.position.getX(), this.position.getY()));
		channelCpy.state = this.state;
		
		return channelCpy;
	}
	
	private Image channelImg = null;
	private Image channelBusyImg = null;
	private Point position;
	private ChannelState state;

}
